﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OKDebug
{
    public class Common
    {
        ////一个字节byte有8个bit位，如：10制的255 = 16进制的0xFF = 8进制的0b_1111_1111
        //byte a = 0xFF; //0b_1111_1111 或 255
        ////例如：设置上面字节a（byte a = 0xFF;）的第8位，设置成0
        //byte b = SetbitValue(a, 8, false);
        //Console.WriteLine(b);//输出0b_0111_1111

        /// <summary>
        /// 设置该字节的某一位的值(将该位设置成0或1)
        /// </summary>
        /// <param name="data">要设置的字节byte</param>
        /// <param name="index">要设置的位， 值从低到高为 1-8</param>
        /// <param name="flag">要设置的值 true(1) / false(0)</param>
        /// <returns></returns>
        public static byte SetbitValue(byte data, int index, bool flag)
        {
            if (index > 8 || index < 1)
                throw new ArgumentOutOfRangeException();
            int v = index < 2 ? index : (2 << (index - 2));
            return flag ? (byte)(data | v) : (byte)(data & ~v);
        }

        /// <summary>
        /// 按名称查找控件
        /// </summary>
        /// <param name="parentControl">查找控件的父容器控件</param>
        /// <param name="findCtrlName">查找控件名称</param>
        /// <returns>若没有查找到返回NULL</returns>
        public static Control FindControl(Control parentControl, string findCtrlName)
        {
            if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)
            {
                foreach (Control ctrl in parentControl.Controls)
                {
                    Control _findedControl;
                    if (ctrl.Name.Equals(findCtrlName))
                    {
                        _findedControl = ctrl;
                        return _findedControl;
                    }
                    else if (ctrl.Controls.Count > 0)
                    {
                        _findedControl = FindControl(ctrl, findCtrlName);
                        if (_findedControl != null)
                        {
                            return _findedControl;
                        }
                    }
                }
            }
            return null;
        }
    }
}
